import {
  AdjustmentsHorizontalIcon,
  ArrowUturnLeftIcon,
  GlobeAltIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import clsx from 'clsx';
import React from 'react';
import { getImage } from 'src/actions/image';
import { IconText } from 'src/components/Icons';
import { Select } from 'src/components/Select';
import { Tabs } from 'src/components/Tabs';

type ImageInfo = NonNullable<Awaited<ReturnType<typeof getImage>>>;

export interface Values {
  width: number;
  height: number;
  fit: 'cover' | 'contain' | 'fill' | 'inside' | 'outside';
  /**
   * 图片质量，取值范围 1-100 整数
   */
  quality?: number;
  /**
   * 图片格式
   */
  format?: string;
  /**
   * 旋转角度，顺时针旋转
   * @example
   * const output = await sharp(input).rotate(90).toBuffer();
   */
  rotate?: number;
  /**
   * 翻转
   * @example
   * const output = await sharp(input).flip().toBuffer(); // 水平翻转
   * const output = await sharp(input).flop().toBuffer(); // 垂直翻转
   * const output = await sharp(input).flip().flop().toBuffer(); // 水平垂直翻转
   */
  flip?: 'horizontal' | 'vertical' | 'both';
  /**
   * 高斯模糊
   */
  blur?: number;
  /**
   * 锐化
   */
  sharpen?: number;
  /**
   * 扩展前景对象：膨胀宽度（以像素为单位）
   * const output = await sharp(input).dilate(1).toBuffer();
   */
  dilate?: number;
  /**
   * 收缩前景对象：侵蚀宽度（以像素为单位）
   * @example
   * const output = await sharp(input).erode(1).toBuffer();
   */
  erode?: number;
  /**
   * 填充透明背景色
   * @example
   * await sharp(rgbaInput).flatten({ background: '#F0A703' }).toBuffer();
   */
  flatten?: string;
  /**
   * 设置透明色（只针对白色背景）
   * @example
   * await sharp(rgbInput).unflatten().toBuffer();
   */
  unflatten?: boolean;
  /**
   * 伽马校正，取值范围：1.0-3.0
   * @example
   * const output = await sharp(input).gamma(2.2).toBuffer();
   */
  gamma?: number;
  /**
   * 增强图像对比度：使暗部更暗，亮部更亮
   * @example
   * const output = await sharp(input).normalize().toBuffer();
   */
  normalize?: boolean;
  /**
   * 增强清晰度：一种高级的对比度增强技术，自动分片调整图像对比度，通过突出更暗的细节来增强图像的清晰度。
   * @example
   * const output = await sharp(input).clahe({ width: 3, height: 3, maxSlope: 3 }).toBuffer();
   */
  clahe?: boolean;
  /**
   * 负片效果：即将图像的颜色反转
   * @example
   * const output = await sharp(input).negate().toBuffer();
   * const output = await sharp(input).negate({ alpha: false }).toBuffer(); // 只反转颜色通道，保持透明度
   */
  negate?: boolean;
  /**
   * 黑白效果：将图像二值化转为黑白图像
   * @example
   * const output = await sharp(input).threshold(128).toBuffer();
   * const output = await sharp(input).threshold({ grayscale: true }).toBuffer(); // 转为灰度图像
   * const output = await sharp(input).threshold({ grayscale: true, threshold: 128 }).toBuffer(); // 转为灰度图像并二值化(黑白图像)
   */
  threshold?: boolean;
  /**
   * 滤镜效果：使用 modulate([options]) 方法来调整图像的色调、饱和度和亮度。这里只提供预设的滤镜选项
   * @example
   * // 奇幻效果：色相旋转120度
   * await sharp(input).modulate({ hue: 120 }).toBuffer();
   * // 复古效果：轻微增加亮度，降低饱和度，微调色相
   * await sharp(input).modulate({ brightness: 1.1, saturation: 0.8, hue: 20 }).toBuffer();
   * // 梦幻效果：增加亮度，降低饱和度，偏蓝色调
   * await sharp(input).modulate({ brightness: 1.2, saturation: 0.7, hue: 210 }).toBuffer();
   */
  filter?: 'fantasy' | 'vintage' | 'dreamy';
  /**
   * 水印
   */
  watermark?: {
    /**
     * 水印图片路径
     */
    image?: string;
    /**
     * 水印文字内容
     */
    text?: string;
    /**
     * 水印位置
     */
    position?:
      | 'centre'
      | 'north'
      | 'northeast'
      | 'east'
      | 'southeast'
      | 'south'
      | 'southwest'
      | 'west'
      | 'northwest';
    /**
     * 水印透明度 (0-1)
     */
    opacity?: number;
    /**
     * 水印与边缘的距离 (x, y)
     */
    offset?: { x: number; y: number };
    /**
     * 水印宽度
     */
    width?: number;
    /**
     * 水印高度
     */
    height?: number;
  };
}

export interface AsideProps {
  ref?: React.Ref<HTMLElement>;
  className?: string;
  imageInfo: ImageInfo;
}

function AsideNoMemoized(props: AsideProps) {
  const { ref, className, imageInfo } = props;

  return (
    <aside
      ref={ref}
      className={clsx(
        'flex flex-col w-72 h-full overflow-hidden border-r border-gray-200 dark:border-neutral-700',
        className
      )}
    >
      <div className="flex-none flex items-center justify-between h-10 p-4 bg-base-100 border-b border-gray-200 dark:border-neutral-700">
        <span className="flex items-center gap-2 text-sm font-bold">
          <AdjustmentsHorizontalIcon className="size-4" />
          工具栏
        </span>
        <button type="button" className="btn btn-xs btn-circle btn-ghost">
          <XMarkIcon className="size-4" />
        </button>
      </div>
      <div className="flex-1 overflow-y-auto overflow-x-hidden">
        <div className="flex flex-col p-2.5 gap-4">
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">调整大小</legend>
            <label className="label">宽度</label>
            <label className="input input-sm">
              <input
                type="number"
                className="grow"
                placeholder="width"
                min="1"
                defaultValue={imageInfo.width ?? undefined}
              />
              <span className="label">像素</span>
            </label>
            <label className="label">高度</label>
            <label className="input input-sm">
              <input
                type="number"
                className="grow"
                placeholder="height"
                min="1"
                defaultValue={imageInfo.height ?? undefined}
              />
              <span className="label">像素</span>
            </label>
            <label className="label">适应模式</label>
            <Select
              size="sm"
              options={[
                { value: 'cover', label: 'Cover' },
                { value: 'contain', label: 'Contain' },
                { value: 'fill', label: 'Fill' },
                { value: 'inside', label: 'Inside' },
                { value: 'outside', label: 'Outside' },
              ]}
              placeholder="请选择适应模式(fit)"
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">输出</legend>
            <label className="label">图片质量（压缩）</label>
            <input type="range" className="range range-primary range-xs" min="1" max="100" />
            <label className="label">格式</label>
            <Select
              size="sm"
              options={[
                { value: 'jpeg', label: 'JPEG' },
                { value: 'png', label: 'PNG' },
                { value: 'webp', label: 'WebP' },
                { value: 'avif', label: 'AVIF' },
                { value: 'gif', label: 'GIF' },
              ]}
              placeholder="请选择输出格式"
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">旋转（顺时针）</legend>
            <label className="input input-sm">
              <input type="number" className="grow" min="0" max="360" step="90" />
              <span className="label">角度</span>
            </label>
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">翻转（镜像翻转）</legend>
            <Select
              size="sm"
              options={[
                { value: 'horizontal', label: '水平翻转' },
                { value: 'vertical', label: '垂直翻转' },
                { value: 'both', label: '水平垂直翻转' },
              ]}
              placeholder="请选择翻转方式"
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">高斯模糊</legend>
            <input type="range" className="range range-primary range-xs" min="1" max="100" />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">锐化</legend>
            <input type="range" className="range range-primary range-xs" min="1" max="100" />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">清晰度（任选一种）</legend>
            <Tabs
              type="border"
              size="xs"
              contentClassName="rounded-none border-none pb-0 pt-5"
              items={[
                {
                  key: 'gamma',
                  label: '伽马校正',
                  children: (
                    <div className="flex flex-col gap-2">
                      <input
                        type="range"
                        className="range range-primary range-xs"
                        min="1"
                        max="100"
                      />
                      <p className="label">伽马校正，调整图像的亮度和对比度</p>
                    </div>
                  ),
                },
                {
                  key: 'normalize',
                  label: '增强对比度',
                  children: (
                    <div className="flex flex-col gap-2">
                      <input type="checkbox" className="toggle toggle-xs" />
                      <p className="label">增强图像对比度，使暗部更暗，亮部更亮</p>
                    </div>
                  ),
                },
                {
                  key: 'clahe',
                  label: '增强清晰度',
                  children: (
                    <div className="flex flex-col gap-2">
                      <input type="checkbox" className="toggle toggle-xs" />
                      <p className="label">使用自适应直方图均衡化增强图像清晰度</p>
                    </div>
                  ),
                },
              ]}
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">背景色（二选一）</legend>
            <Tabs
              type="border"
              size="xs"
              contentClassName="rounded-none border-none pb-0 pt-5"
              items={[
                {
                  key: 'fill',
                  label: '填充背景色',
                  children: (
                    <div className="flex flex-col gap-2">
                      <input type="color" className="input input-sm w-32" />
                      <p className="label">填充透明背景为指定颜色</p>
                    </div>
                  ),
                },
                {
                  key: 'transparent',
                  label: '透明背景色',
                  children: (
                    <div className="flex flex-col gap-2">
                      <input type="checkbox" className="toggle toggle-xs" />
                      <p className="label">将白色背景转换为透明背景</p>
                    </div>
                  ),
                },
              ]}
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">预设效果（任选一种）</legend>
            <Tabs
              type="border"
              size="xs"
              contentClassName="rounded-none border-none pb-0 pt-5"
              items={[
                {
                  key: 'whiteBlack',
                  label: '黑白效果',
                  children: (
                    <div className="flex gap-2">
                      <input type="checkbox" className="toggle toggle-xs" />
                      <p className="label">将图像转换为黑白</p>
                    </div>
                  ),
                },
                {
                  key: 'negate',
                  label: '负片效果',
                  children: (
                    <div className="flex gap-2">
                      <input type="checkbox" className="toggle toggle-xs" />
                      <p className="label">将图像颜色反转</p>
                    </div>
                  ),
                },
                {
                  key: 'filter',
                  label: '滤镜',
                  children: (
                    <Select
                      size="sm"
                      options={[
                        { value: 'fantasy', label: '奇幻效果' },
                        { value: 'vintage', label: '复古效果' },
                        { value: 'dreamy', label: '梦幻效果' },
                      ]}
                      placeholder="请选择滤镜"
                    />
                  ),
                },
              ]}
            />
          </fieldset>
          <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
            <legend className="fieldset-legend">高级用法</legend>
            <label className="label">扩展前景对象</label>
            <label className="input input-sm">
              <input type="number" className="grow" min="0" max="100" placeholder="膨胀宽度" />
              <span className="label">像素</span>
            </label>
            <label className="label">收缩前景对象</label>
            <label className="input input-sm">
              <input type="number" className="grow" min="0" max="100" placeholder="侵蚀宽度" />
              <span className="label">像素</span>
            </label>
            <fieldset className="fieldset bg-base-100 border-base-300 rounded-box w-full border p-4 pt-2">
              <legend className="fieldset-legend">水印</legend>
              <Tabs
                type="border"
                size="xs"
                contentClassName="rounded-none border-none px-0 py-3"
                items={[
                  {
                    key: 'image',
                    label: '水印图片',
                    children: (
                      <div className="flex flex-col gap-2">
                        <label className="input input-sm">
                          <GlobeAltIcon className="size-4" />
                          <input type="text" className="grow" placeholder="水印图片路径" />
                        </label>
                        <p className="label">支持站内图片或网络图片</p>
                      </div>
                    ),
                  },
                  {
                    key: 'text',
                    label: '水印文字',
                    children: (
                      <div className="flex flex-col gap-2">
                        <label className="input input-sm">
                          <IconText className="size-4" />
                          <input type="text" className="grow" placeholder="水印文字" />
                        </label>
                        <p className="label">支持自定义水印文字</p>
                      </div>
                    ),
                  },
                ]}
              />
              <label className="label">水印位置</label>
              <Select
                size="sm"
                options={[
                  { value: 'centre', label: '中心' },
                  { value: 'north', label: '北' },
                  { value: 'northeast', label: '东北' },
                  { value: 'east', label: '东' },
                  { value: 'southeast', label: '东南' },
                  { value: 'south', label: '南' },
                  { value: 'southwest', label: '西南' },
                  { value: 'west', label: '西' },
                  { value: 'northwest', label: '西北' },
                ]}
                placeholder="请选择水印位置"
              />
              <label className="label">水印透明度</label>
              <input
                type="range"
                className="range range-primary range-xs"
                min="0"
                max="1"
                step="0.01"
              />
              <label className="label">水印偏移</label>
              <div className="flex flex-col gap-2">
                <label className="input input-sm">
                  <input type="number" className="grow" min="0" placeholder="X 偏移" />
                  <span className="label">像素</span>
                </label>
                <label className="input input-sm">
                  <input type="number" className="grow" min="0" placeholder="Y 偏移" />
                  <span className="label">像素</span>
                </label>
              </div>
              <label className="label">水印宽度</label>
              <label className="input input-sm">
                <input type="number" className="grow" min="1" placeholder="水印宽度" />
                <span className="label">像素</span>
              </label>
              <label className="label">水印高度</label>
              <label className="input input-sm">
                <input type="number" className="grow" min="1" placeholder="水印高度" />
                <span className="label">像素</span>
              </label>
            </fieldset>
          </fieldset>
        </div>
      </div>
      <div className="flex-none h-10 flex items-center justify-center bg-base-100 border-t border-gray-200 dark:border-neutral-700">
        <span className="label text-xs">应用更改后操作才会生效并预览，但不会保存</span>
      </div>
      <div className="flex-none h-12 p-4 bg-base-100 flex items-center justify-end gap-2">
        <button
          type="button"
          className="btn btn-ghost btn-sm rounded-full"
          onClick={() => {
            // 重置表单逻辑
            console.log('重置表单');
          }}
        >
          <ArrowUturnLeftIcon className="size-4" />
          重置
        </button>
        <button
          type="button"
          className="btn btn-primary btn-sm rounded-full"
          onClick={() => {
            // 提交表单逻辑
            console.log('提交表单');
          }}
        >
          应用更改
        </button>
      </div>
    </aside>
  );
}

export const Aside = React.memo(AsideNoMemoized);
